const express = require('express');
const router = express.Router();
const superagent = require('superagent');
const cheerio = require('cheerio');

router.get('/', async (req, res) => {
    
  try {
    console.log('hot0');
    const targetUrl = "https://top.baidu.com/board?tab=realtime";
    // 模拟浏览器请求头‌:ml-citation{ref="3" data="citationList"}
    const headers = {
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36..."
    };
    // 发送HTTP请求‌:ml-citation{ref="1,2" data="citationList"}
    const response = await superagent.get(targetUrl).set(headers);
    
    const $ = cheerio.load(response.text);
    
    // 解析DOM结构‌:ml-citation{ref="2" data="citationList"}
    const hotList = [];
    $('div.category-wrap_iQLoo').each((index, element) => {
      if (index < 10) { // Only consider the first 10 elements
        const title = $(element).find('div.c-single-text-ellipsis').text().trim();
        const hotIndex = $(element).find('div.hot-index_1Bl1a').text().trim();
        hotList.push({ rank: index + 1, title, hotIndex });
      }
    });
    res.status(200).send({
        code:200,
        list:hotList,
        msg:'获取成功'
    });
  } catch (error) {
    res.status(500).json({ error: '数据抓取失败' });
  }
});

module.exports = router;
